package boot.controller.interceptor;

/**
 * @author cb
 * @create 2022-09-14-10:22
 */
import boot.util.JwtUtil;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object hander) throws Exception {
        response.setCharacterEncoding("UTF-8");
        //Authorization参数是前台放在headler中的key
        String token = request.getHeader("Authorization");
        if(token != null){
            Claims claims = JwtUtil.parseJWT(token);
            System.out.println(claims);
            if(claims!=null){
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        //返回的数据
        JSONObject res = new JSONObject();
        res.put("status","-1");
        res.put("msg","need login");
        PrintWriter out = null ;
        out = response.getWriter();
        out.write(res.toString());
        out.flush();
        out.close();
        return false;
    }
}


